<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<style type="text/css">
body {
	font-family: Segoe UI,Arial,Verdana,Tahoma,sans-serif;
	font-size: 6mm;
}

a {
	height:10.5ex;   
    width:10.5ex;  
    float:left;
    margin:0.8ex 0.8ex 0 0;
    padding:0.2ex;
    background-color: #2E8B57;
    color: #fff;
    text-decoration: none;
}

#myDisplay {
	font-size: 9mm;
	font-stretch: condensed;
	font-weight: lighter;
  max-width: 15ex;
	word-wrap: break-word;
}

input, select {
	font-size: 5mm;
}
</style>
<script type="text/javascript">
var timers = new Array();
var timelapsed = 0;

function crono(valor_inicial, nome) {
	this.valor_inicial = valor_inicial;
	this.nome = nome;
	this.valor = valor_inicial;
	this.tv = valor_inicial;
	this.sub_crono = new Array();
	this.running = false;
	this.UNIT = 1000;
 	this.clear = function clear() {
 		this.running=false;
 		timelapsed = 0;
		this.timeover();
 	};

 	this.x = function x(new_crono) {
		this.sub_crono = this.sub_crono.concat(new_crono);
		this.tv = this.total_valor();
	};

	this.subtr = function subtr() {
			this.valor--;
			timelapsed++;
			this.display(this.valor, this.nome);
	};

	this.reset = function reset() {
			this.valor = this.valor_inicial;
			timelapsed++;
			this.display_bip(this.valor, this.nome);
	};

	this.total_valor = function total_valor() {
		var res = 0;
		if (this.sub_crono.length == 0) {
			return this.valor;
		} else {
			for(var m=0; m<this.sub_crono.length; m++) {
				res = res + this.sub_crono[m].tv;
			}
			return this.valor * res;
		}
	};

	this.total_sub_pre = function total_sub_pre(pre) {
		var res = 0;
		if (this.sub_crono.length == 0) {
			return this.valor;
		} else {
			for(var r=0; r<pre; r++) {
				res = res + this.sub_crono[r].tv;
			}
			return res;
		}
	};

	this.total_sub_pos = function total_sub_pos(pos) {
		var res = 0;
		if (this.sub_crono.length == 0) {
			return this.valor;
		} else {
			for(var q=pos+1; q<this.sub_crono.length; q++) {
				res = res + this.sub_crono[q].tv;
			}
			return res;
		}
	};

	this.countdown = function countdown(lasttime) {
		if (lasttime>timelapsed) {
			var self = this;
			if (timelapsed>(lasttime-this.valor_inicial)) {
				for(var p=1; p<this.valor; p++) {
					timers.push(setTimeout(function() { self.subtr(); }, (lasttime-p-timelapsed)*this.UNIT));
				}
			} else {
				for(var p=1; p<this.valor_inicial; p++) {
					timers.push(setTimeout(function() { self.subtr(); }, (lasttime-p-timelapsed)*this.UNIT));
				}
				timers.push(setTimeout(function() { self.reset(); }, (lasttime-this.valor_inicial-timelapsed)*this.UNIT));
			}			
		}
	};

	this.run = function run(times, lag, lag2, delay) {
		if (this.sub_crono.length == 0) {
			for (var k=times; k>0; k--) {
				this.countdown(lag+lag2*k+this.valor_inicial*k+delay*(k-1));
			}
		} else {
			for (var i=0; i<times; i++) {
				for (var j=0; j<this.sub_crono.length; j++) {
					this.sub_crono[j].run(this.valor_inicial, lag+lag2+i*(this.tv+lag2+delay), this.total_sub_pre(j), this.total_sub_pos(j));
				}
			}
		}
	};
	
	this.abort = function abort() {
		for(this.clear();timers.length>0;clearTimeout(timers.pop()));
	};
	
	this.pause = function pause() {
		this.running = false;
		for(;timers.length>0;clearTimeout(timers.pop()));
	};

	this.play = function play() {
		this.run(1,0,0,0);
		this.running = true;
		var self = this;
		timers.push(setTimeout(function () { self.clear(); }, (this.tv-timelapsed)*this.UNIT));
	};
}
</script>
<script type="text/javascript">
/**
 * 
 * Gramática ABNF (http://tools.ietf.org/html/rfc5234) que define uma expressão válida:
 * script =  expr *("," [SP] expr)                ; uma expressao ou uma sequência delas
 * expr   =  [1*DIGIT %x27] 1*DIGIT DQUOTE *ALPHA ; minutos e segundos ou só segundos...
 * expr   =/ 1*DIGIT %x27 *ALPHA                  ; ...ou só minutos
 * expr   =/ 1*DIGIT "(" script ")"               ; ou uma repetição sobre um script
 *
 */
var SCRIPTRULE = /((((\d+\')?\d+\")|(\d+\'))\w*)|(\d+\(.+\))/g;
var IS_GRP = /\d+\(.+\)/;
var GRP_CONTENT = /\(.+(?=\))/;
var MIN = /\d+(?=\')/;
var SEC = /\d+(?=\")/;
function leiaTokens (expressao) {
	var tokenlist = expressao.match(SCRIPTRULE);
	for (var token in tokenlist) {
		if (IS_GRP.test(tokenlist[token])) {
			var multiplicador = new crono(tokenlist[token].match(/^\d+/)[0]);
			conteudo = tokenlist[token].match(GRP_CONTENT)[0].slice(1);
			multiplicador.x(leiaTokens(conteudo));
			tokenlist[token] = multiplicador;
		} else {
			tempo = 0;
			if (MIN.test(tokenlist[token])) {
				tempo += parseInt(tokenlist[token].match(MIN)[0])*60;
			}
			if (SEC.test(tokenlist[token])) {
				tempo += parseInt(tokenlist[token].match(SEC)[0]);
			}
			nome = tokenlist[token].match(/\w*$/)[0];
			tokenlist[token] = new crono(tempo, nome);
		}
	}
	return tokenlist;
}

function script (expr) {
	var cronoarray = leiaTokens(expr);
	if (cronoarray.length > 1) {
		var newcrono = new crono(1);
		newcrono.x(cronoarray);
		return newcrono;
	}
	return cronoarray[0];
}
</script>
<script type="text/javascript">
/**
 * Created by: http://gustavopaes.net
 * Created on: Nov/2009
 * 
 * Retorna os valores de parâmetros passados via url.
 *
 * @param String Nome da parâmetro.
 */
function _GET(name)
{
  var url   = window.location.search.replace("?", "");
  var itens = url.split("&");

  for(n in itens)
  {
    if( itens[n].match(name) )
    {
      return decodeURIComponent(itens[n].replace(name+"=", ""));
    }
  }
  return null;
}
</script>
<script type="text/javascript">

//variáveis globais 
var txtscript = "";
var myscript = null;
var editing = false;
var inserting = false;
var grp = 0;

/** 
 * como e onde serão apresentados os dígitos do cronômetro
 */
 crono.prototype.display = function (seconds, timername) { //não alterar esta linha
	if (seconds>59) {
		document.getElementById("myDisplay").innerHTML = Math.floor(seconds/60) + ":";
		if (seconds%60<10) document.getElementById("myDisplay").innerHTML += "0";
		document.getElementById("myDisplay").innerHTML += seconds%60 + "<br>" + timername;
	} else {
		document.getElementById("myDisplay").innerHTML = seconds + "<br>" + timername;
	}
 }
 
/** 
 * um cronometro (re)inicia
 */
 crono.prototype.display_bip = function (seconds, timername) { //não alterar esta linha
	//mostra normalmente 
	this.display(seconds, timername);
	//toca um sonzinho ;)
	document.getElementById("myDisplay").innerHTML += "<audio autoplay=\"autoplay\"><source src=\"bip.mp3\" type=\"audio/mp3\" /><source src=\"bip.ogg\" type=\"audio/ogg\" /></audio>";
 }

/** 
 * o script encerra ou é abortado
 */
 crono.prototype.timeover = function () { //não alterar esta linha
	document.getElementById("myDisplay").innerHTML = txtscript;
 	btnUpdt();
 }

/** 
 * Dispara a ações do botão '+/set/reset/abort'
 */
 function btnSetPress() {
	if (timelapsed>0) {
		myscript.abort();
	} else {
		if (editing) { 
			inserting = true;
		} else { 
			txtscript = "";
			editing = true;
		}
	}
	btnUpdt();
 }

/** 
 * Dispara a ações do botão 'play/pause/)/Ok'
 */
 function btnCtrlPress() {
	if (myscript.running) {
		myscript.pause();
	} else {
		if (editing) {
			if (grp==0) {
				editing = false;
			} else {
				txtscript += ")";
				grp--;	
			} 
		} else {
			myscript.play();
		}
	}
	btnUpdt();
 };

 /** 
  * atualiza elementos de tela: botoes, formulário e painel
  */
 function btnUpdt() {
	var CTRLBTN = document.getElementById("ctrlBtn");
	var SETBTN = document.getElementById("setBtn");
	if (myscript.running) {
		CTRLBTN.innerHTML = '<a href="javascript:btnCtrlPress()" >pause</a>';
		SETBTN.innerHTML = '<a href="javascript:btnSetPress()" >abort</a>';
	} else {
		if (editing) {
			if (txtscript!="") {
				document.getElementById("myDisplay").innerHTML = txtscript;
			} else {
				document.getElementById("myDisplay").innerHTML = "N&atilde;o h&aacute; script";
			}
			if (inserting) {
				CTRLBTN.innerHTML = "";
				SETBTN.innerHTML = "";
				frmEditUpdt();
			} else {
				document.getElementById("editFrm").innerHTML="";
				if (grp>0) {
					if (txtscript.slice(-1)!="(") {
						CTRLBTN.innerHTML = '<a href="javascript:btnCtrlPress()" >)</a>';
					} else {
						CTRLBTN.innerHTML = "";
					}
				} else {
					if (txtscript!="") {
						CTRLBTN.innerHTML = '<a href="javascript:btnCtrlPress()" >Ok</a>';
					} else {
						CTRLBTN.innerHTML = "";
					}
				}
				SETBTN.innerHTML = '<a href="javascript:btnSetPress()" >+</a>';
			}
		} else {
			CTRLBTN.innerHTML = '<a href="javascript:btnCtrlPress()" >play</a>';
			if (timelapsed==0) {
				SETBTN.innerHTML = '<a href="javascript:btnSetPress()" >set</a>';
				if (txtscript!="") {
					myscript = script(txtscript);
				}
			} else {
				SETBTN.innerHTML = '<a href="javascript:btnSetPress()" >reset</a>';
			}
		}
	}
 }

 function init() {
	 txtscript = _GET('script');
	 if (txtscript!=null) {
		 myscript = script(txtscript);
		 document.getElementById("myDisplay").innerHTML = txtscript;
	 } else {
		 myscript = new crono(0);
		 txtscript = "";
		 document.getElementById("myDisplay").innerHTML = "N&atilde;o h&aacute; script";
	 }
	 btnUpdt();
 }
 
 function btnInputPress() {
	 var valida = false;
	 var txtent = "";
	 if ((txtscript != "")&&(txtscript.slice(-1)!="(")) {
		 txtent = ",";
	 }
	 if (document.getElementsByName("tipo")[0].checked) {
		 if (parseInt(document.getElementById("minutos").value)>0) {
			 txtent += document.getElementById("minutos").value + "'";
			 valida = true;
		 }
		 if (parseInt(document.getElementById("segundos").value)>0) {
			 txtent += document.getElementById("segundos").value + '"';
			 valida = true;
		 }
		 if (valida) {
			 txtscript += txtent + document.getElementById("titulo").value;
		 }
	 } else {
		 if (parseInt(document.getElementById("multiplica").value)>0) {
			 grp++;
			 txtscript += txtent + document.getElementById("multiplica").value + "(";
		 }
	 }
	 inserting = false;
	 btnUpdt();
 }

 function frmEditUpdt () {
	 var frmContador = '<select id="minutos"><option selected="selected" value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select>&prime;&nbsp;<select id="segundos"><option selected="selected" value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="20">20</option><option value="30">30</option></select>&Prime;<br><input type="text" size="12" id="titulo"><br><input type="radio" name="tipo" value="contador" checked="checked" onclick="javascript:frmEditUpdt()">Contador<br><input type="radio" name="tipo" value="multiplicador" onclick="javascript:frmEditUpdt()">Multiplicador<br><a href="javascript:btnInputPress()" >Ok</a>';
	 var frmMultiplicador = '<select id="multiplica"><option selected="selected" value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select><br><input type="radio" name="tipo" value="contador" onclick="javascript:frmEditUpdt()">Contador<br><input type="radio" name="tipo" checked="checked" value="multiplicador" onclick="javascript:frmEditUpdt()">Multiplicador<br><a href="javascript:btnInputPress()" >Ok</a>';
	 var frmEdit = document.getElementById("editFrm"); 
	 if (frmEdit.innerHTML=="") {
		 frmEdit.innerHTML = frmContador;
	 } else if (document.getElementsByName("tipo")[0].checked) {
		 frmEdit.innerHTML = frmContador;
	 } else {
		 frmEdit.innerHTML = frmMultiplicador; 
	 }
 }
</script>
</head>
<body onload="javascript:init()">
<div id="myDisplay"></div>
<span id="setBtn"></span>
<span id="ctrlBtn"></span>
<div id="editFrm"></div>
</body>
</html>
